import React, { useCallback, useMemo, useRef, useState } from 'react'
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious
} from './pagination'
import { Button } from './button'
import { Input } from './input'

interface PagerProps {
  page: number
  total: number
  pageSize: number
  onPageChange: (page: number) => void
  isPageLoading?: boolean
}

/**
 * 通用分页组件，支持小屏和大屏自适应，页码逻辑与 BattleList 保持一致
 */
export const Pager: React.FC<PagerProps> = ({
  page,
  total,
  pageSize,
  onPageChange,
  isPageLoading
}) => {
  // 边界处理
  const safePageSize = Math.max(1, pageSize)
  const pageCount = Math.max(1, Math.ceil(total / safePageSize))
  const safePage = Math.min(Math.max(1, page), pageCount)

  // 跳转页码输入框（桌面端）
  const [inputPage, setInputPage] = useState<string>('')
  const inputRef = useRef<HTMLInputElement>(null)
  // 防止loading时重复点击，增加防抖
  const debounceRef = useRef<NodeJS.Timeout | null>(null)
  const handlePageChange = useCallback(
    (p: number) => {
      if (isPageLoading || p === safePage) return
      if (debounceRef.current) clearTimeout(debounceRef.current)
      debounceRef.current = setTimeout(() => {
        onPageChange(p)
      }, 100)
    },
    [isPageLoading, safePage, onPageChange]
  )

  const handleJump = useCallback(() => {
    let num = parseInt(inputPage, 10)
    if (isNaN(num)) return
    num = Math.max(1, Math.min(pageCount, num))
    setInputPage('')
    if (num !== safePage) handlePageChange(num)
  }, [inputPage, pageCount, safePage, handlePageChange])

  const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleJump()
    }
  }

  // 页码数组
  const mobilePages = useMemo(() => {
    const arr: number[] = []
    if (safePage > 1) arr.push(safePage - 1)
    arr.push(safePage)
    if (safePage < pageCount) arr.push(safePage + 1)
    return arr
  }, [safePage, pageCount])

  const desktopPages = useMemo(() => {
    const arr: (number | string)[] = []
    if (pageCount <= 7) {
      for (let i = 1; i <= pageCount; i++) arr.push(i)
    } else {
      arr.push(1)
      if (safePage > 4) arr.push('left-ellipsis')
      const start = Math.max(2, safePage - 2)
      const end = Math.min(pageCount - 1, safePage + 2)
      for (let i = start; i <= end; i++) arr.push(i)
      if (safePage < pageCount - 3) arr.push('right-ellipsis')
      arr.push(pageCount)
    }
    return arr
  }, [safePage, pageCount])

  if (pageCount <= 1) return null

  return (
    <div className="flex justify-center">
      {/* 移动端分页 */}
      <div className="block md:hidden">
        <Pagination>
          <PaginationContent>
            <PaginationItem>
              <PaginationPrevious
                aria-disabled={safePage === 1 || isPageLoading}
                tabIndex={safePage === 1 || isPageLoading ? -1 : 0}
                onClick={() => {
                  if (safePage === 1 || isPageLoading) return
                  handlePageChange(safePage - 1)
                }}
                aria-label="上一页"
                className={
                  safePage === 1 || isPageLoading ? '' : 'cursor-pointer'
                }
              />
            </PaginationItem>
            {mobilePages.map((p) => (
              <PaginationItem key={`m-${p}`}>
                <PaginationLink
                  isActive={safePage === p}
                  aria-current={safePage === p ? 'page' : undefined}
                  tabIndex={safePage === p ? -1 : 0}
                  onClick={() => {
                    if (safePage === p || isPageLoading) return
                    handlePageChange(p)
                  }}
                  aria-label={`第${p}页`}
                  className={
                    safePage === p || isPageLoading ? '' : 'cursor-pointer'
                  }
                >
                  {p}
                </PaginationLink>
              </PaginationItem>
            ))}
            <PaginationItem>
              <PaginationNext
                aria-disabled={safePage === pageCount || isPageLoading}
                tabIndex={safePage === pageCount || isPageLoading ? -1 : 0}
                onClick={() => {
                  if (safePage === pageCount || isPageLoading) return
                  handlePageChange(safePage + 1)
                }}
                aria-label="下一页"
                className={
                  safePage === pageCount || isPageLoading
                    ? ''
                    : 'cursor-pointer'
                }
              />
            </PaginationItem>
          </PaginationContent>
        </Pagination>
      </div>
      {/* 桌面端分页 */}
      <div className="hidden md:block">
        <Pagination>
          <PaginationContent>
            <PaginationItem>
              <PaginationPrevious
                aria-disabled={safePage === 1 || isPageLoading}
                tabIndex={safePage === 1 || isPageLoading ? -1 : 0}
                onClick={() => {
                  if (safePage === 1 || isPageLoading) return
                  handlePageChange(safePage - 1)
                }}
                aria-label="上一页"
                className={
                  safePage === 1 || isPageLoading ? '' : 'cursor-pointer'
                }
              />
            </PaginationItem>
            {desktopPages.map((p) => {
              if (p === 'left-ellipsis' || p === 'right-ellipsis') {
                return (
                  <PaginationItem key={p}>
                    <PaginationEllipsis />
                  </PaginationItem>
                )
              }
              if (typeof p === 'number') {
                return (
                  <PaginationItem key={`d-${p}`}>
                    <PaginationLink
                      isActive={safePage === p}
                      aria-current={safePage === p ? 'page' : undefined}
                      tabIndex={safePage === p ? -1 : 0}
                      onClick={() => {
                        if (safePage === p || isPageLoading) return
                        handlePageChange(p)
                      }}
                      aria-label={`第${p}页`}
                      className={
                        safePage === p || isPageLoading ? '' : 'cursor-pointer'
                      }
                    >
                      {p}
                    </PaginationLink>
                  </PaginationItem>
                )
              }
              return null
            })}
            <PaginationItem>
              <PaginationNext
                aria-disabled={safePage === pageCount || isPageLoading}
                tabIndex={safePage === pageCount || isPageLoading ? -1 : 0}
                onClick={() => {
                  if (safePage === pageCount || isPageLoading) return
                  handlePageChange(safePage + 1)
                }}
                aria-label="下一页"
                className={
                  safePage === pageCount || isPageLoading
                    ? ''
                    : 'cursor-pointer'
                }
              />
            </PaginationItem>
            {/* 跳转到指定页码 */}
            <PaginationItem>
              <div className="ml-2 flex items-center gap-2">
                <Input
                  ref={inputRef}
                  type="number"
                  min={1}
                  max={pageCount}
                  value={inputPage}
                  onChange={(e) => {
                    // 允许清空输入框
                    const val = e.target.value.replace(/[^\d]/g, '')
                    setInputPage(val)
                  }}
                  onFocus={() => {
                    // 不自动填充当前页，允许用户清空
                  }}
                  onBlur={() => {
                    // 失焦时不自动还原当前页，允许用户清空
                  }}
                  onKeyDown={handleInputKeyDown}
                  className="h-9 w-16 text-center text-sm"
                  placeholder={safePage.toString()}
                  aria-label="跳转页码"
                  disabled={isPageLoading}
                  style={{ minWidth: 0 }}
                />
                <Button
                  type="button"
                  className={[
                    'h-9 px-4 rounded-md border border-transparent bg-transparent text-primary text-sm font-normal flex items-center justify-center hover:bg-accent hover:border-accent focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-50 transition-colors',
                    !(
                      isPageLoading ||
                      !inputPage ||
                      isNaN(Number(inputPage)) ||
                      Number(inputPage) === safePage
                    )
                      ? 'cursor-pointer'
                      : ''
                  ].join(' ')}
                  onClick={handleJump}
                  disabled={
                    isPageLoading ||
                    !inputPage ||
                    isNaN(Number(inputPage)) ||
                    Number(inputPage) === safePage
                  }
                  tabIndex={isPageLoading ? -1 : 0}
                  style={{ minWidth: '3.5rem' }}
                >
                  跳转
                </Button>
              </div>
            </PaginationItem>
          </PaginationContent>
        </Pagination>
      </div>
    </div>
  )
}
